package com.smm.web.vmc.service.impl;

import com.smm.web.vmc.dao.BaseDao;
import com.smm.web.vmc.domain.Alam;
import com.smm.web.vmc.domain.Receipt;
import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.domain.relation.CameraReceiptRelation;
import com.smm.web.vmc.domain.relation.UserReceiptRelation;
import com.smm.web.vmc.dto.AlamQueryDto;
import com.smm.web.vmc.dto.ReceiptDto;
import com.smm.web.vmc.dto.UserDto;
import com.smm.web.vmc.service.CameraReceiptRelationService;
import com.smm.web.vmc.service.ReceiptService;
import com.smm.web.vmc.service.UserReceiptRelationService;
import com.smm.web.vmc.service.UserService;
import com.smm.web.vmc.util.MD5Util;
import com.smm.web.vmc.util.SendMailUtil;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhenghao on 2016/8/29.
 * 用户操作实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private BaseDao<User> userBaseDao;

    @Resource
    private ReceiptService receiptService;

    @Resource
    private UserReceiptRelationService userReceiptRelationService;

    @Resource
    private CameraReceiptRelationService cameraReceiptRelationService;

    //新用户注册绑定仓单编号
    @Value("${new.user.band.repNo}")
    private String bandRepNo ;


    @Override
    public User login(String account, String password) throws Exception {

        password = MD5Util.parseStrToMd5L32(password);

        DetachedCriteria where = DetachedCriteria.forClass(User.class);
        where.add(Restrictions.eq("account", account));
        where.add(Restrictions.eq("password", password));

        List<User> users = userBaseDao.query(where);

        if(users==null || users.size()==0) return null;

        return users.get(0);
    }

    @Override
    public User regist(UserDto user) throws Exception {


        User dbUser = new User();

        BeanUtils.copyProperties(user,dbUser);

        //用户密码2次md5
        dbUser.setPassword(MD5Util.parseStrToMd5L32(dbUser.getPassword()));

        //写入注册时间
        dbUser.setRegistTime(new Date());

        userBaseDao.add(dbUser);



        //注册成功，关联指定仓单（有色仓库，指定编号仓单）
//        List<String> repNoList = new ArrayList<>();
//
//        repNoList.add(bandRepNo);
//
//        this.choiseReceipt(dbUser.getId(),repNoList);

//        2018-5-21  取消新用户注册绑定默认仓单

        //新用户注册，发送邮件通知管理员
        SendMailUtil.sendCommonMail("zhangjianfeng@smm.cn","移动监控-新用户注册通知","有新的用户注册，请查看并授权！注册帐号："+user.getAccount());

        return dbUser;
    }

    @Override
    public List<ReceiptDto> getAllReceiptByUser(int userId) {
        return null;
    }

    @Override
    public List<Alam> getAllAlamByUser(int userId) {
        return null;
    }

    @Override
    public List<Alam> queryAlam(int userId, AlamQueryDto query) {
        return null;
    }

    @Override
    public void updatePassword(int userId, String newPassword) throws Exception {


    }

    @Override
    @Transactional
    public List<UserDto> getAllForDto() {
        String sql = "SELECT user.*,COUNT(userreceiptrelation.`receipt_no`) as recepitNumber FROM `user` \nLEFT JOIN userreceiptrelation ON userreceiptrelation.`user_id` = user.`id`\nGROUP BY `user`.`id` order BY `user`.`id` desc";
        List result = this.userBaseDao.createSqlQuery(sql);
        if(result != null && result.size() != 0) {
            ArrayList userDtoList = new ArrayList();
            Iterator var4 = result.iterator();

            while(var4.hasNext()) {
                Object[] obj = (Object[])var4.next();
                UserDto dto = new UserDto();
                dto.setId(Integer.parseInt(obj[0].toString()));
                dto.setAccount(obj[1].toString());
                dto.setPassword(obj[2].toString());
                dto.setPhone(obj[3].toString());
                dto.setRealName(obj[4].toString());
                dto.setRegistTime((Date)obj[5]);
                dto.setRecepitNumber(Integer.parseInt(obj[7].toString()));
                userDtoList.add(dto);
            }

            return userDtoList;
        } else {
            return null;
        }
    }

    @Override
    public User getOneById(int userId) {

        return userBaseDao.getOne(User.class,userId);
    }

    @Override
    public void choiseReceipt(int userId, List<String> repNoList) throws Exception {

        if(userId==0) throw new Exception("用户id为空");

        //删除用户原有仓单关联
        userReceiptRelationService.deleteByUer(userId);

        //新增新的关联
        if(repNoList!=null && repNoList.size()>0){

            UserReceiptRelation relation = new UserReceiptRelation();

            User user = userBaseDao.getOne(User.class,userId);

            for(String no: repNoList){

                relation.setUser(user);
                relation.setReceipt(receiptService.getOneById(no));

                userReceiptRelationService.add(relation);
            }


        }

    }

    @Override
    public void update(User user) throws Exception {

        this.userBaseDao.update(user);
    }

    @Override
    public boolean checkPurviewForCamera(int userId, int cameraId) {

        //通过摄像头与仓单的关联关系，找出对应仓单
        List<CameraReceiptRelation> crrList = this.cameraReceiptRelationService.getAllByCamera(cameraId);

        if(crrList==null || crrList.size()==0) return false;

        //检查会员与仓单是否存在关联关系
        for(CameraReceiptRelation crr: crrList){

            UserReceiptRelation relation = this.userReceiptRelationService.getReceiptByUserAndRepNo(userId,crr.getReceipt().getNo());

            //只要有一个关联关系存在，就表示当前用户有权限访问摄像头
            if(relation!=null) return true;
        }

        return false;
    }

    @Override
    public void updateUserPhone(int userId, String phone) throws Exception {

        if(phone==null) throw new Exception("手机号码不能为空");

        User user = this.userBaseDao.getOne(User.class,userId);

        if(user==null) throw new Exception("编号为："+userId+" 的用户不存在");

        user.setPhone(phone.trim());

        this.userBaseDao.update(user);

    }


}
